package baduga.karo;

import javax.swing.JOptionPane;

import baduga.client.Controler;
import baduga.client.Game_Cfg;
import baduga.client.Player_Constans;
import baduga.core.Core_Gui_ErrorWindow;
import baduga.core.Core_JsonDataSchema;
import baduga.core.Core_Messages;

import java.awt.Toolkit;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;



//klasa z okienkiem do zakładania nowego stołu


/**
* @author Karolina
*/
public class CreateNewTable extends javax.swing.JFrame {

	private static final long serialVersionUID = 1L;
	boolean successTable = false;
	
	
	private Controler contr;
  
	//zmiana ikonki na pasku tytułu
  public CreateNewTable(Controler newVar) {
	  contr = newVar;
	  

	  
  	setIconImage(Toolkit.getDefaultToolkit().getImage(CreateNewTable.class.getResource("/baduga/karo/resources/icon.png")));
      initComponents();
  }
  
  
  
  int timeToMove = 0;
  int cash = 0;
  int bigBlind = 0;
  int smallBlind = 0;
  int numberPlayers = 0;
  int numberObs = 0;
  String tableName = "";
  
  @SuppressWarnings("unchecked")
                      
  private void initComponents() {
  	//dodajemy główne pola na ekranie
      jLabelCreateTabel = new JLabel();
      jButtonOK = new JButton();
      jButtonCancel = new JButton();
      jLabelRequirement = new JLabel();
      minimumCash = new JTextField();
      jLabel1 = new JLabel();
      jTextFieldBigBlindValue = new JTextField();
      jLabel2 = new JLabel();
      jTextFieldSmallBlindValue = new JTextField();
      jLabel3 = new JLabel();
      jTextFieldNumberOfPlayers = new JTextField();
      jLabel4 = new JLabel();
      jTextFieldNumberOfObs = new JTextField();
      jButton1 = new JButton();
      jLabel5 = new JLabel();
      jTextFieldTableName = new JTextField();
      textField = new JTextField();
      textField.setColumns(10);
      setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
      setTitle("Nowy stolik");

      jLabelCreateTabel.setFont(new java.awt.Font("Tahoma", 1, 18));
      jLabelCreateTabel.setText("Utwórz nowy stół");
      
      //obsługa przycisków "ok", "anuluj" i "wyczyść"
      
      jButtonOK.setText("OK");
      jButtonOK.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButtonOKActionPerformed(evt);
          }
      });

      jButtonCancel.setText("Anuluj");
      jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButtonCancelActionPerformed(evt);
          }
      });
      
      jButton1.setText("Wyczyść");
      jButton1.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButton1ActionPerformed(evt);
          }
      });

      //TODO: Dodać potem pobieranie aktualnej kwoty
      //wyświetlanie instrukcji dla gracza wraz z kryteriami wyboru
      
      
      
      
      //proponujemy domyślną nazwę stołu - wolną nazwę z dużym p-stwem daje nam wylosowanie liczb i dopisanie ich iloczynu
      
      jLabel5.setText("Podaj nazwę stołu ( "+Game_Cfg.TAB_NAME_LIM[0]+" - "+Game_Cfg.TAB_NAME_LIM[1]+" znaków )");
      
      
      
      int tmpLimit;
      jLabelRequirement.setText("Podaj minimalna ilość żetonów, jaką musi mieć grać aby usiąsć ( "+ Game_Cfg.VALUE_BIG_BLIND[0] +" - " + Player_Constans.getCash() + " )");

      
      tmpLimit =  setCorrectLimit( Game_Cfg.VALUE_SMALL_BLIND[1] );
      jLabel1.setText("Podaj wartość małej ciemnej ( "+Game_Cfg.VALUE_SMALL_BLIND[0]+" - " + tmpLimit + " )");
      
      
      tmpLimit =  setCorrectLimit( Game_Cfg.VALUE_BIG_BLIND[1] );
      jLabel2.setText("Podaj wartość dużej ciemnej ( "+Game_Cfg.VALUE_BIG_BLIND[0]+" - " + tmpLimit + " )");

      
      jLabel3.setText("Podaj ilość graczy ( "+Game_Cfg.TAB_PLAYER_LIM[0]+" - "+Game_Cfg.TAB_PLAYER_LIM[1]+" )");
      jLabel4.setText("Podaj ilość obserwatorów ( "+Game_Cfg.TAB_OBSERV_LIM[0]+" - "+Game_Cfg.TAB_OBSERV_LIM[1]+" )");

      final JLabel lblPodajCzasNa = new JLabel("Podaj czas na ruch gracza ("+Game_Cfg.PLAYER_MOVE_TIME[0]+" - "+Game_Cfg.PLAYER_MOVE_TIME[1]+" s)");
      
      
      int first = (int)(Math.random() * 100);
      int second = (int)(Math.random()*100);
      
      int tableAddition = first * second * first * second;
   
      //ustawienie wartości domyślnych pozostałych pól
      
      /**
       * Konfiguracja wartości domyślnych
       * 
       */
      
      
      jTextFieldTableName.setText("Stół "+tableAddition);
      
      minimumCash.setText( Integer.toString( setCorrectLimit( Game_Cfg.VALUE_BIG_BLIND[0] ) ) );
      jTextFieldSmallBlindValue.setText( Integer.toString( setCorrectLimit( Game_Cfg.VALUE_SMALL_BLIND[2] ) )   );
      jTextFieldBigBlindValue.setText( Integer.toString( setCorrectLimit( Game_Cfg.VALUE_BIG_BLIND[2] ) ) );
      
      
      jTextFieldNumberOfPlayers.setText( Integer.toString( Game_Cfg.TAB_PLAYER_LIM[0] ) );
      
      jTextFieldNumberOfObs.setText( Integer.toString( Game_Cfg.TAB_OBSERV_LIM[2] ) );
      
      
      textField.setText(""+Game_Cfg.PLAYER_MOVE_TIME[2]);
      


      
      
      
      //ustalenie parametrów graficznych okna
      
      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      layout.setHorizontalGroup(
      	layout.createParallelGroup(Alignment.LEADING)
      		.addGroup(layout.createSequentialGroup()
      			.addContainerGap(23, Short.MAX_VALUE)
      			.addGroup(layout.createParallelGroup(Alignment.LEADING)
      				.addComponent(jLabelCreateTabel, GroupLayout.PREFERRED_SIZE, 226, GroupLayout.PREFERRED_SIZE)
      				.addGroup(layout.createSequentialGroup()
      					.addGap(10)
      					.addGroup(layout.createParallelGroup(Alignment.LEADING)
      						.addComponent(jLabel5, GroupLayout.PREFERRED_SIZE, 204, GroupLayout.PREFERRED_SIZE)
      						.addComponent(jTextFieldTableName, GroupLayout.PREFERRED_SIZE, 293, GroupLayout.PREFERRED_SIZE)
      						.addComponent(jLabelRequirement)
      						.addComponent(minimumCash, GroupLayout.PREFERRED_SIZE, 295, GroupLayout.PREFERRED_SIZE)
      						.addGroup(layout.createSequentialGroup()
      							.addComponent(jButtonOK, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE)
      							.addGap(18)
      							.addComponent(jButtonCancel)
      							.addGap(18)
      							.addComponent(jButton1)))))
      			.addGap(74)
      			.addGroup(layout.createParallelGroup(Alignment.LEADING)
      				.addComponent(jTextFieldBigBlindValue, GroupLayout.PREFERRED_SIZE, 237, GroupLayout.PREFERRED_SIZE)
      				.addComponent(jLabel2, GroupLayout.PREFERRED_SIZE, 273, GroupLayout.PREFERRED_SIZE)
      				.addComponent(jTextFieldSmallBlindValue, GroupLayout.PREFERRED_SIZE, 237, GroupLayout.PREFERRED_SIZE)
      				.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 295, GroupLayout.PREFERRED_SIZE)
      				.addGroup(layout.createSequentialGroup()
      					.addGroup(layout.createParallelGroup(Alignment.LEADING)
      						.addComponent(jLabel3)
      						.addComponent(lblPodajCzasNa)
      						.addComponent(jLabel4))
      					.addGap(12)
      					.addGroup(layout.createParallelGroup(Alignment.LEADING, false)
      						.addComponent(textField, 0, 0, Short.MAX_VALUE)
      						.addComponent(jTextFieldNumberOfObs, GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
      						.addComponent(jTextFieldNumberOfPlayers)))))
      );
      layout.setVerticalGroup(
      	layout.createParallelGroup(Alignment.LEADING)
      		.addGroup(layout.createSequentialGroup()
      			.addGroup(layout.createParallelGroup(Alignment.TRAILING)
      				.addGroup(layout.createSequentialGroup()
      					.addComponent(jLabelCreateTabel, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE)
      					.addGap(11))
      				.addGroup(layout.createSequentialGroup()
      					.addGroup(layout.createParallelGroup(Alignment.BASELINE)
      						.addComponent(lblPodajCzasNa)
      						.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
      					.addPreferredGap(ComponentPlacement.RELATED)))
      			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
      				.addComponent(jLabel3)
      				.addComponent(jTextFieldNumberOfPlayers, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
      				.addComponent(jLabel5))
      			.addPreferredGap(ComponentPlacement.RELATED)
      			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
      				.addComponent(jLabel4, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)
      				.addComponent(jTextFieldNumberOfObs, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
      				.addComponent(jTextFieldTableName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
      			.addPreferredGap(ComponentPlacement.RELATED)
      			.addGroup(layout.createParallelGroup(Alignment.LEADING)
      				.addComponent(jLabelRequirement)
      				.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE))
      			.addPreferredGap(ComponentPlacement.RELATED)
      			.addGroup(layout.createParallelGroup(Alignment.LEADING)
      				.addComponent(minimumCash, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
      				.addComponent(jTextFieldSmallBlindValue, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
      			.addPreferredGap(ComponentPlacement.RELATED)
      			.addComponent(jLabel2, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE)
      			.addPreferredGap(ComponentPlacement.RELATED)
      			.addComponent(jTextFieldBigBlindValue, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
      			.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
      				.addComponent(jButtonOK)
      				.addComponent(jButtonCancel)
      				.addComponent(jButton1))
      			.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      );
      getContentPane().setLayout(layout);

      pack();
  }
  
  //wczytuje wejściowe parametry stołu takie jak ilość graczy, mała, duża ciemna, nazwa stołu etc.
  
  private int giveCashRequirement() {

      try {
          cash = Integer.parseInt(minimumCash.getText());
      } catch (NumberFormatException e) {
      }
      return cash;

  }

  private int giveBigBlindRequirement() {

      try {
          bigBlind = Integer.parseInt(jTextFieldBigBlindValue.getText());
      } catch (NumberFormatException e) {
      }
      return bigBlind;

  }

  private int numberPlayersRequirement() {

      try {
          numberPlayers = Integer.parseInt(jTextFieldNumberOfPlayers.getText());
      } catch (NumberFormatException e) {
      }
      return numberPlayers;
  }
      
  private int numberObsRequirement() {

      try {
          numberObs = Integer.parseInt(jTextFieldNumberOfObs.getText());
      } catch (NumberFormatException e) {
      }
      return numberObs;
  }
  
  private String tableNameRequirement() {

      tableName = jTextFieldTableName.getText();
      
      return tableName;
  }
  private int giveSmallBlindRequirement() {

      try {
          smallBlind = Integer.parseInt(jTextFieldSmallBlindValue.getText());
      } catch (NumberFormatException e) {
      }
      return smallBlind;

  }
  
  private int giveTimeToMove() {

      try {
          timeToMove = Integer.parseInt(textField.getText());
      } catch (NumberFormatException e) {
      }
      return timeToMove;

  }
  //sprawdzenie poprawności wpisanych parametrów
  
  private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {  
  	giveCashRequirement();
      giveSmallBlindRequirement();
      giveBigBlindRequirement();
      numberPlayersRequirement();
      numberObsRequirement();
      tableNameRequirement();
      giveTimeToMove();
      
      //TODO:Dodać potem pobieranie aktualnej kwoty
      //W miejsce drugie warunkou będzie aktualna kwota gracza.
      
      
      /** Zbiera wszystkie ostrzeżenia */
      String sumOfWarning = "";
      
      
      int tmpLimit;
      
      
      
      /**
       * 
       * Sprawdzenie wymagań odnośnie minmalnej kwoty na wejście do stołu
       * 
       */
 
      if (cash < Game_Cfg.VALUE_BIG_BLIND[0] ||  cash >  Player_Constans.getCash() ) {
    	  sumOfWarning += Core_Messages.getMessage(0x01FF) + "\n";
      }
      
      /**
       * 
       * Sprawdzenie wymagań odnośnie VALUE_SMALL_BLIND
       * 
       */

      tmpLimit =  setCorrectLimit( Game_Cfg.VALUE_SMALL_BLIND[1]);
      
      if (smallBlind < Game_Cfg.VALUE_SMALL_BLIND[0] || smallBlind > tmpLimit) {
    	  sumOfWarning += Core_Messages.getMessage(0x01FE) + "\n";
      }
      
      /**
       * 
       * Sprawdzenie wymagań odnośnie VALUE_BIG_BLIND
       * 
       */
      
      tmpLimit =  setCorrectLimit( Game_Cfg.VALUE_BIG_BLIND[1] );
      
      
      if (bigBlind < Game_Cfg.VALUE_BIG_BLIND[0] || bigBlind > tmpLimit) {
    	  sumOfWarning += Core_Messages.getMessage(0x01FD) + "\n";
      }
      
      /**
       * 
       * Sprawdzenie wymagań odnośnie TAB_OBSERV_LIM
       * 
       */
      
      
      
      if (numberObs < Game_Cfg.TAB_OBSERV_LIM[0] || numberObs > Game_Cfg.TAB_OBSERV_LIM[1]) {
    	  sumOfWarning += Core_Messages.getMessage(0x01FC) + " \n";
      }
      
      
      /**
       * 
       * Sprawdzenie wymagań odnośnie TAB_PLAYER_LIM
       * 
       */
      
      
      if (numberPlayers < Game_Cfg.TAB_PLAYER_LIM[0] || numberPlayers > Game_Cfg.TAB_PLAYER_LIM[1]) {
    	  sumOfWarning += Core_Messages.getMessage(0x01FB) + " \n";
      }
      
      
      /**
       * 
       * Sprawdzenie wymagań odnośnie TAB_NAME_LIM
       * 
       */
      
      if (tableName.length() < Game_Cfg.TAB_NAME_LIM[0] || tableName.length() > Game_Cfg.TAB_NAME_LIM[1]) {
    	  sumOfWarning += Core_Messages.getMessage(0x01FA) + "\n";
      }
      
      
      /**
       * 
       * Sprawdzenie wymagań odnośnie PLAYER_MOVE_TIME
       * 
       */
      
      
      if (timeToMove < Game_Cfg.PLAYER_MOVE_TIME[0] || timeToMove > Game_Cfg.PLAYER_MOVE_TIME[1]) {
    	  sumOfWarning += Core_Messages.getMessage(0x01F9) + " \n";
      }
      
      
      //Jeżeli nie ma komunikatów błędu tworzy okno gry, w przeciwnym razie wyświetla error. log
      if(sumOfWarning.isEmpty()) 
      {
    	  
    	//Próba wysłania danych stołu do serwera
      	if(!contr.fSendData( prepateTableData() ))
      	{
      		Core_Gui_ErrorWindow.errorWindow(Core_Messages.getMessage(0x02F3), Core_Messages.getMessage(0x0100));
      	}
    	  
      }
      else
      {
    	  Core_Gui_ErrorWindow.errorWindow(sumOfWarning, Core_Messages.getMessage(0x0100));
      }
  }
     //obsługa przycisku "wyczyść" - czyscimy wszystkie pola tekstowe    
  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
	minimumCash.setText("");
	jTextFieldBigBlindValue.setText("");
	jTextFieldNumberOfPlayers.setText("");
	jTextFieldNumberOfObs.setText("");
	jTextFieldTableName.setText("");
	jTextFieldSmallBlindValue.setText("");
	textField.setText("");
	
  }
      
  
  
  /**
   * Obsługa przycisku anuluj
   * 
   * @param evt
   */
  private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {                                              
      this.dispose();
      
      
      
      Controler.guiTabListScr = new TableListScreen(contr);
      
      Controler.guiTabListScr.setVisible(true);
      Controler.guiTabListScr.setLocationRelativeTo(null);
      
  }    
  
  
  
  
  /**
   * Funkcja przyjmuje przedział [nax] -> zwaraca [max] or [Player_Constans.getCash()] 
   * 
   * @param max
   * @return
   */
  private int  setCorrectLimit(final int max)
  {
	  return max <= Player_Constans.getCash() ? max : Player_Constans.getCash();
  }

  
  
  private Core_JsonDataSchema prepateTableData()
  {
  	Core_JsonDataSchema data = new Core_JsonDataSchema();
  	
  	//Ustawienie kodu
  	data.setKod(0x04);
  	
  	//Ustawienie argumentów
  	data.setArgs
  	(
  			new int[] {
  					0x01
  			}
  	);
  	
  	
  	//Ustawienie danych
  	data.setDataD1
  	(
  		new Object[] {
  			Player_Constans.getPlayerID()
  		}
  	);
  	
  	
  	//Ustawienie danych
  	data.setDataD2
  	(
  		new Object[][] {
  			new Object[] {
  				2, 					//Min. il. graczy
  				numberPlayers,		//Max. il. graczy
  				numberObs,			//Max. il. obs
  				cash,				//Min. il. żetonów, aby wejśc do gry
  				smallBlind,			//Wart. małej w ciemno
  				bigBlind,			//Wart. dużej w ciemno
  				timeToMove			//Czas na ruch gracza
  				
  			},
  			new Object[] {
  				tableName,			//Nazwa stołu
  				"",					//Opis
  				""					//Hasło
  			}
  		}
  	);
  	
  	return data;
  	
  }
  
  
  
  
  /**
   * Zwraca Kontroler
   * 
   * @return
   */
  public Controler getControler()
  {
  	return this.contr;
  }
  

                 
  private JButton jButton1;
  private JButton jButtonCancel;
  private JButton jButtonOK;
  private JLabel jLabel1;
  private JLabel jLabel2;
  private JLabel jLabel3;
  private JLabel jLabel4;
  private JLabel jLabel5;
  private JLabel jLabelCreateTabel;
  private JLabel jLabelRequirement;
  private JTextField jTextFieldBigBlindValue;
  private JTextField jTextFieldNumberOfObs;
  private JTextField jTextFieldNumberOfPlayers;
  private JTextField jTextFieldSmallBlindValue;
  private JTextField jTextFieldTableName;
  private JTextField minimumCash;
  private JTextField textField;
}
